package com.xx.sg.controller;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xx.sg.controller.req.FireJudge;
import com.xx.sg.own.entity.Dept;
import com.xx.sg.own.entity.FireInfo;
import com.xx.sg.own.entity.FireInfoHandle;
import com.xx.sg.own.service.DeptService;
import com.xx.sg.own.service.FireInfoHandleService;
import com.xx.sg.own.service.FireInfoService;
import com.xx.sg.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/fireInfo")
@Tag(name = "防火组件预警", description = "防火组件预警API")
public class FireInfoController {

    @Value("${hk.host}")
    private String HK_HOST;
    @Value("${hk.key}")
    private String HK_KEY;
    @Value("${hk.secret}")
    private String HK_SECRET;
    @Value("${hk.artemis-path}")
    private String ARTEMIS_PATH;

    @Autowired
    private DeptService deptService;
    @Autowired
    private FireInfoService fireInfoService;
    @Autowired
    private FireInfoHandleService fireInfoHandleService;

    @PostMapping("/judgeList")
    public JSONObject judgeList(@RequestBody FireJudge fireJudge) throws Exception {

        ArtemisConfig config = new ArtemisConfig();
        config.setHost(HK_HOST); // 代理API网关nginx服务器ip端口
        config.setAppKey(HK_KEY);  // 秘钥appkey
        config.setAppSecret(HK_SECRET);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/bforestfire/v1/alarms/judge/list";

        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        System.out.println(fireJudge.toJsonStr());
        String response = ArtemisHttpUtil.doPostStringArtemis(config, path, fireJudge.toJsonStr(),
                null, null, "application/json;charset=UTF-8");
        return JSONObject.parseObject(response);
    }

    @PostMapping("/add")
    @Operation(summary = "火情上报", description = "火情上报")
    public R add(@RequestBody FireInfo fireInfo) {
        Dept dept = deptService.selectDeptByPoint(fireInfo.getLongitude(), fireInfo.getLatitude());
        if (dept == null) {
            fireInfo.setRegionId("00115");
        } else {
            fireInfo.setRegionId(dept.getId());
        }

        fireInfoService.save(fireInfo);

        FireInfoHandle handle = FireInfoHandle.builder()
                .alarmId(fireInfo.getId())
                .content("火情上报")
                .build();
        fireInfoHandleService.save(handle);
        return R.success();
    }

    @PostMapping("/modifyPosition")
    @Operation(summary = "位置纠偏", description = "位置纠偏")
    public R modifyPosition(@RequestBody FireInfo fireInfo) {
        LambdaUpdateWrapper<FireInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(FireInfo::getId, fireInfo.getId())
                .set(fireInfo.getLongitude() != null, FireInfo::getLongitude, fireInfo.getLongitude())
                .set(fireInfo.getLatitude() != null, FireInfo::getLatitude, fireInfo.getLatitude())
                .set(StringUtils.isNotBlank(fireInfo.getMemo()), FireInfo::getMemo, fireInfo.getMemo());
        fireInfoService.update(wrapper);

        FireInfoHandle handle = FireInfoHandle.builder()
                .alarmId(fireInfo.getId())
                .content("位置纠偏")
                .build();
        fireInfoHandleService.save(handle);
        return R.success();
    }

    @PostMapping("/endFire")
    @Operation(summary = "结束火情", description = "结束火情")
    public R endFire(@RequestBody FireInfo fireInfo) {
        LambdaUpdateWrapper<FireInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(FireInfo::getId, fireInfo.getId())
                .set(FireInfo::getStatus,"已处置");
        fireInfoService.update(wrapper);

        FireInfoHandle handle = FireInfoHandle.builder()
                .alarmId(fireInfo.getId())
                .content("结束火情")
                .build();
        fireInfoHandleService.save(handle);
        return R.success();
    }

    @PostMapping("/confirmFireInfo")
    @Operation(summary = "火情确认", description = "火情确认")
    public R confirmFireInfo(@RequestBody FireInfo fireInfo) {
        LambdaUpdateWrapper<FireInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(FireInfo::getId, fireInfo.getId())
                .set(FireInfo::getStatus, fireInfo.getResult().equals("确认") ? "待处置" : "已处置")
                .set(FireInfo::getCheckedDatetime, LocalDateTime.now())
                .set(StringUtils.isNotBlank(fireInfo.getResult()), FireInfo::getResult, fireInfo.getResult())
                .set(StringUtils.isNotBlank(fireInfo.getResultType()), FireInfo::getResultType, fireInfo.getResultType())
                .set(StringUtils.isNotBlank(fireInfo.getResultReason()), FireInfo::getResultReason, fireInfo.getResultReason())
                .set(StringUtils.isNotBlank(fireInfo.getResultMemo()), FireInfo::getResultMemo, fireInfo.getResultMemo());
        fireInfoService.update(wrapper);

        FireInfoHandle handle = FireInfoHandle.builder()
                .alarmId(fireInfo.getId())
                .content(fireInfo.getResult())
                .build();
        fireInfoHandleService.save(handle);
        return R.success();
    }

    @PostMapping("/issueFireInfo")
    @Operation(summary = "下发任务", description = "下发任务")
    public R issueFireInfo(@RequestBody FireInfoHandle handle) {
        LambdaUpdateWrapper<FireInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(FireInfo::getId, handle.getAlarmId())
                .set(FireInfo::getStatus, "核查中");
        fireInfoService.update(wrapper);
        handle.setContent("下发任务");
        fireInfoHandleService.save(handle);
        return R.success();
    }

    @PostMapping("/repeatFireInfo")
    @Operation(summary = "重复火情", description = "重复火情")
    public R issueFireInfo(@RequestBody FireInfo fireInfo) {
        LambdaUpdateWrapper<FireInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(FireInfo::getId, fireInfo.getId())
                .set(FireInfo::getStatus, "已处置")
                .set(FireInfo::getRepeatFireId, fireInfo.getRepeatFireId())
                .set(FireInfo::getCheckedDatetime, LocalDateTime.now());
        fireInfoService.update(wrapper);

        FireInfoHandle handle = FireInfoHandle.builder()
                .alarmId(fireInfo.getId())
                .content("重复火情")
                .build();
        fireInfoHandleService.save(handle);
        return R.success();
    }

    @PostMapping("/checkFireInfo")
    @Operation(summary = "核实火情", description = "核实火情")
    //待写
    public R checkFireInfo(@RequestBody FireInfo fireInfo) {

        return R.success();
    }

    @PostMapping("/list")
    @Operation(summary = "列表查询", description = "列表查询")
    public R list(@RequestBody FireInfo fireInfo) {
        LambdaUpdateWrapper<FireInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(fireInfo.getClassify()), FireInfo::getClassify, fireInfo.getClassify())
                .eq(StringUtils.isNotBlank(fireInfo.getStatus()), FireInfo::getStatus, fireInfo.getStatus())
                .eq(StringUtils.isNotBlank(fireInfo.getResult()), FireInfo::getResult, fireInfo.getResult())
                .eq(StringUtils.isNotBlank(fireInfo.getName()), FireInfo::getName, fireInfo.getName())
                .eq(StringUtils.isNotBlank(fireInfo.getRegionId()), FireInfo::getRegionId, fireInfo.getRegionId())
                .in(fireInfo.getStatusList() != null, FireInfo::getStatus, fireInfo.getStatusList())
                .apply(StringUtils.isNotBlank(fireInfo.getDay()), "to_char(datetime,'YYYY-MM-DD')={0}", fireInfo.getDay())
                .orderByDesc(FireInfo::getDatetime);
        return R.success(fireInfoService.list(wrapper));
    }

    @PostMapping("/page")
    @Operation(summary = "列表分页查询", description = "列表分页查询")
    public R page(@RequestParam(defaultValue = "1") Integer current,
                  @RequestParam(defaultValue = "10") Integer size,
                  @RequestBody FireInfo fireInfo) {

        LambdaUpdateWrapper<FireInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(fireInfo.getClassify()), FireInfo::getClassify, fireInfo.getClassify())
                .eq(StringUtils.isNotBlank(fireInfo.getStatus()), FireInfo::getStatus, fireInfo.getStatus())
                .eq(StringUtils.isNotBlank(fireInfo.getResult()), FireInfo::getResult, fireInfo.getResult())
                .eq(StringUtils.isNotBlank(fireInfo.getName()), FireInfo::getName, fireInfo.getName())
                .eq(StringUtils.isNotBlank(fireInfo.getRegionId()), FireInfo::getRegionId, fireInfo.getRegionId())
                .in(fireInfo.getStatusList() != null, FireInfo::getStatus, fireInfo.getStatusList())
                .apply(StringUtils.isNotBlank(fireInfo.getDay()), "date_format(datetime,'%Y-%m-%d)={0}", fireInfo.getDay())
                .orderByDesc(FireInfo::getDatetime);
        Page<FireInfo> page = new Page<>(current, size);
        fireInfoService.page(page, wrapper);
        return R.success(page);
    }

    @GetMapping("/fireInfoHandle/{fireId}")
    @Operation(summary = "查询火情处理流程", description = "查询火情处理流程")
    public R fireInfoHandle(@PathVariable("fireId") String fireId) {
        return R.success(fireInfoHandleService.selectByFireInfoHandle(FireInfoHandle.builder().alarmId(fireId).build()));
    }

    @GetMapping("/fireInfoHandle")
    @Operation(summary = "查询火情处理流程", description = "查询火情处理流程")
    public R fireInfoHandle(FireInfoHandle fireInfoHandle) {
        return R.success(fireInfoHandleService.selectByFireInfoHandle(fireInfoHandle));
    }
}
